package de.isibboi.cassandraintro;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.template.ColumnFamilyTemplate;
import me.prettyprint.cassandra.service.template.ColumnFamilyUpdater;
import me.prettyprint.cassandra.service.template.ThriftColumnFamilyTemplate;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.exceptions.HectorException;

/**
 * A command-line program that can store key-value pairs to Cassandra.
 * 
 * @author Sebastian Schmidt
 */
public class CassandraWriter {
	/**
	 * Starts the program.
	 * 
	 * @param args
	 *            Program arguments.
	 */
	public static void main(String[] args) {
		Collection<String[]> data = parseArgs(args);

		Keyspace keyspace = CassandraUtil.getKeyspace(CassandraUtil.KEYSPACE, CassandraUtil.COLUMN_FAMILY);

		ColumnFamilyTemplate<String, String> template = new ThriftColumnFamilyTemplate<String, String>(keyspace,
				CassandraUtil.COLUMN_FAMILY, StringSerializer.get(), StringSerializer.get());

		for (String[] pair : data) {
			ColumnFamilyUpdater<String, String> updater = template.createUpdater(pair[0]);
			updater.setString("value", pair[1]);
			try {
				template.update(updater);
			} catch (HectorException e) {
				printUsageAndExit("An error occurred during insertion: " + e.getMessage());
			}
		}
	}

	/**
	 * Parses the command line arguments.
	 * 
	 * @param args
	 *            The command line arguments.
	 * @return The result as string-arrays, position 0 being the key, position 1
	 *         the value.
	 */
	private static Collection<String[]> parseArgs(String[] args) {
		List<String[]> arguments = new LinkedList<>();

		for (String arg : args) {
			String[] pair = arg.split("\\s*=\\s*");

			if (pair.length != 2) {
				printUsageAndExit("Illegal Argument format.");
			} else {
				arguments.add(pair);
			}
		}

		return arguments;
	}

	/**
	 * Prints some usage information and exits the program. This method never
	 * returns.
	 * 
	 * @param error
	 *            An error message to print.
	 */
	private static void printUsageAndExit(String error) {
		System.out.println("Error: " + error);
		System.out.println("Format: java -jar <yourjarname.jar> <name>=<value> [<name>=<value> ...]");
		System.out.println("Neither 'name' nor 'value' are allowed to be emtpy or to contain a '='.");

		System.exit(-1);
	}
}